package com.zkk.tankgame04;

import java.io.*;
import java.util.Vector;

/**
 *工具类
 * 该类用于记录相关信息，和文件交互
 * */
public class Recorder {
    //定义变量，记录我方击毁敌方坦克数
    private static int allEnemyTankNum = 0;
    //定义IO对象，准备写数据到文件中
    private static FileWriter fw = null;
    private static BufferedWriter bw = null;
    private static BufferedReader br = null;
    private static String recordFile = "src\\myRecord.txt";
    //定义Vector，执向MyPanel对象的敌人坦克容器
    private static Vector<EnemyTank> enemyTanks = null;
    //定义一个Node的Vector容器，用于存放敌人的信息
    private static Vector<Node> nodes = new Vector<>();
    public static Vector<EnemyTank> getEnemyTanks() {
        return enemyTanks;
    }

    public static String getRecordFile() {
        return recordFile;
    }

    //读取recordeFile恢复相关信息
    public static Vector<Node> getNodesAndEnemyTankRec(){
        try {
           br = new BufferedReader(new FileReader(recordFile));
           Recorder.allEnemyTankNum = Integer.parseInt(br.readLine());
           //循环读取文件 生成nodes集合
            String line = "";
            while((line = br.readLine()) != null){
                String[] xyz = line.split(" ");
                Node node = new Node(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]),
                        Integer.parseInt(xyz[2]));
                nodes.add(node);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return nodes;
    }

    public static void setEnemyTanks(Vector<EnemyTank> enemyTanks) {
        Recorder.enemyTanks = enemyTanks;
    }

    //当游戏退出时，我们将allEnemyTankNum 保存到文件中去
    //对keepRecorder进行升级，保存敌人坦克的坐标和方向
    public static void keepRecord(){
        try {
            bw = new BufferedWriter(new FileWriter(recordFile));
            bw.write(allEnemyTankNum + "\r\n");
            //遍历敌人坦克的Vector根据情况保存
            for (int i = 0; i < enemyTanks.size(); i++) {
                EnemyTank enemyTank = enemyTanks.get(i);
                if (enemyTank.isLive){
                    //保存的信息
                    String record = enemyTank.getX() + " " + enemyTank.getY() + " " + enemyTank.getDirect();
                    //写入文件
                    bw.write(record + "\r\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static int getAllEnemyTankNum() {
        return allEnemyTankNum;
    }

    public static void setAllEnemyTankNum(int allEnemyTankNum) {
        Recorder.allEnemyTankNum = allEnemyTankNum;
    }
    //当我方击毁一个敌人坦克时，就应当 allEnemyTankNum++
    public static void addAllEnemyTankNum(){
        Recorder.allEnemyTankNum++;
    }
}
